//
//  QSTabScrollView.swift
//  TestSwift
//
//  Created by Song on 2019/2/25.
//  Copyright © 2019 Song. All rights reserved.
//

import UIKit

/// 代理
protocol QSTabScrollViewDelegate: class {
    /// 滚动视图
    ///
    /// - Parameters:
    ///   - scrollView: scrollView
    ///   - pageIndex: 页码
    func qs_tabScrollView(_ scrollView: QSTabScrollView, pageIndex: Int)
}

class QSTabScrollView: UIScrollView {
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    convenience init(viewsArray: Array<UIView>) {
        self.init(frame: .zero)
        self.setValue(viewsArray, forKey: "qs_viewsArray")
        
        // 停止滚动
        self.qs_didEndScroll = { (scrView) in
            guard let _ = self.qs_delegate?.qs_tabScrollView(self, pageIndex: scrView.qs_horizontalPageIndex) else { return }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 使用kvc，undefine方法
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        if key == "qs_viewsArray" { // 设置viewsArray
            guard let newValue = value as? Array<UIView> else {
                return
            }
            
            viewsArray = newValue
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 布局
        var lastView = UIView.init()
        for i in 0 ..< viewsArray.count {
            let view = viewsArray[i]
            self.addSubview(view)
            view.snp.makeConstraints { (make) in
                if i == 0 {
                    make.left.equalTo(0.0)
                } else {
                    make.left.equalTo(lastView.snp.right).offset(0.0)
                }
                make.width.equalTo(self.frame.width)
                make.height.equalTo(self.frame.height)
                make.top.bottom.equalTo(0.0)
                if i == (viewsArray.count - 1) {
                    make.right.equalTo(0.0)
                }
            }
            
            lastView = view
        }
    }
    
    // MARK: - Propertys
    /// views数组
    var viewsArray: Array<UIView> = Array<UIView>.init()
    
    /// 代理
    weak var qs_delegate: QSTabScrollViewDelegate?
}
